<template>
  <view class="page">
    <!-- Tab栏 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{ active: activeTab === index }"
        @click="switchTab(index)"
      >
        <text class="tab-text">{{ tab.name }}</text>
        <view class="tab-badge" v-if="getBadgeCount(index) > 0">
          {{ getBadgeCount(index) }}
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="order-list" scroll-y lower-threshold="60" @scrolltolower="loadMore">
      <view class="order-item" v-for="order in orderList" :key="order.id" @click="goToDetail(order)">
        <view class="order-header">
          <view class="order-no-wrapper">
            <text class="order-no">订单号：{{ order.orderNo }}</text>
            <text class="order-type-tag">{{ getCategoryName(order) }}</text>
          </view>
          <text class="order-status" :style="{ color: getStatusColor(order.settlementStatus) }">
            {{ getSettlementStatusText(order.settlementStatus) }}
          </text>
        </view>

        <view class="order-body">
          <!-- 用户信息 -->
          <view class="user-info">
            <view class="info-row">
              <text class="label">接单人:</text>
              <text class="value">{{ order.deliveryUserName || '未知' }}</text>
            </view>
            <view class="info-row">
              <text class="label">联系电话:</text>
              <text class="value">{{ order.deliveryUserPhone || '-' }}</text>
            </view>
          </view>

          <!-- 结算信息 -->
          <view class="settlement-info">
            <!-- 正常订单显示完整费用结构 -->
            <template v-if="order.status !== 8">
              <view class="amount-row">
                <text class="label">订单金额:</text>
                <text class="amount">¥{{ order.actualAmount }}</text>
              </view>
              <view class="amount-row">
                <text class="label">平台服务费:</text>
                <text class="fee">-¥{{ order.platformFee }}</text>
              </view>
              <view class="amount-row highlight">
                <text class="label">结算金额:</text>
                <text class="settlement-amount">¥{{ order.riderEarning }}</text>
              </view>
            </template>
            
            <!-- 退款订单显示补偿信息 -->
            <template v-else>
              <view class="amount-row">
                <text class="label">原订单金额:</text>
                <text class="amount">¥{{ order.actualAmount }}</text>
              </view>
              <view class="amount-row refund">
                <text class="label">已退款:</text>
                <text class="fee">-¥{{ order.refundAmount }}</text>
              </view>
              <view class="amount-row highlight">
                <text class="label">补偿结算:</text>
                <text class="settlement-amount">¥{{ order.riderEarning }}</text>
              </view>
            </template>
          </view>
        </view>

        <view class="order-footer">
          <view class="order-time">
            <text>{{ order.confirmTime || order.createTime }}</text>
          </view>
          <view class="order-actions">
            <view class="btn btn-primary" v-if="order.settlementStatus === 1" @click.stop="handleSettle(order)">
              确认结算
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="orderList.length === 0 && !loading">
        <text class="empty-icon">💰</text>
        <text class="empty-text">暂无结算订单</text>
      </view>

      <!-- 加载更多 -->
      <view class="loadmore" v-if="orderList.length > 0">
        <text class="loadmore-text">{{ loadingText }}</text>
      </view>
    </scroll-view>

    <!-- 结算详情弹窗 -->
    <view class="settlement-modal" v-if="showSettlementModal" @click="closeSettlementModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">💰 结算信息</text>
          <text class="modal-close" @click="closeSettlementModal">✕</text>
        </view>

        <scroll-view scroll-y class="modal-body" enable-flex>
          <view class="modal-body-content">
          <!-- 结算金额 -->
          <view class="settlement-amount-section">
            <view class="amount-label">结算金额</view>
            <view class="amount-value">¥{{ currentOrder.riderEarning }}</view>
            <view class="amount-tip">请向接单人转账此金额</view>
          </view>

          <!-- 收款信息 -->
          <view class="payment-info-section">
            <view class="section-title">📋 收款信息</view>
            
            <view class="info-item">
              <view class="item-label">收款方式</view>
              <view class="item-value">{{ currentOrder.paymentMethod || '-' }}</view>
            </view>

            <view class="info-item">
              <view class="item-label">收款人姓名</view>
              <view class="item-value">{{ currentOrder.paymentAccount || '-' }}</view>
            </view>

            <view class="info-item">
              <view class="item-label">联系电话</view>
              <view class="item-value">
                {{ currentOrder.paymentPhone || currentOrder.deliveryUserPhone || '-' }}
              </view>
            </view>

            <!-- 收款码图片 -->
            <view class="qrcode-section" v-if="currentOrder.paymentQrCode">
              <view class="qrcode-title">💳 收款码</view>
              <view class="qrcode-wrapper" @click="previewQrCode">
                <image 
                  class="qrcode-image" 
                  :src="currentOrder.paymentQrCode" 
                  mode="aspectFit"
                />
              </view>
              <view class="qrcode-tip">👆 点击图片可放大扫码</view>
            </view>

            <!-- 备注信息 -->
            <view class="info-item" v-if="currentOrder.remark">
              <view class="item-label">备注信息</view>
              <view class="item-value remark">{{ currentOrder.remark }}</view>
            </view>
          </view>

          <!-- 订单信息 -->
          <view class="order-info-section">
            <view class="section-title">📦 其他信息</view>
            
            <view class="info-row-simple">
              <text class="row-label">接单人：</text>
              <text class="row-value">{{ currentOrder.deliveryUserName || '未知' }}</text>
            </view>

            <view class="info-row-simple">
              <text class="row-label">订单号：</text>
              <text class="row-value">{{ currentOrder.orderNo }}</text>
            </view>

            <view class="info-row-simple">
              <text class="row-label">申请时间：</text>
              <text class="row-value">{{ currentOrder.settlementApplyTime || '-' }}</text>
            </view>
          </view>
          </view>
        </scroll-view>

        <!-- 操作按钮 -->
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeSettlementModal">取消</button>
          <button class="btn-confirm" @click="confirmSettle">确认已转账</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getPickupOrderPage, getSettlementInfo, settleOrder } from '@/api/pickup'

export default {
  data() {
    return {
      tabs: [
        { name: '待结算', status: 1 },  // 申请中的订单才需要商家处理
        { name: '已结算', status: 2 }
      ],
      activeTab: 0,
      orderList: [],
      badgeCount: {
        pending: 0
      },
      page: 1,
      pageSize: 10,
      loading: false,
      finished: false,
      showSettlementModal: false,
      currentOrder: {}
    }
  },
  
  computed: {
    loadingText() {
      if (this.loading) return '加载中...'
      if (this.finished) return '没有更多了'
      return '上拉加载更多'
    }
  },
  
  onLoad() {
    this.loadOrders()
  },
  
  onShow() {
    // 刷新列表
    this.page = 1
    this.finished = false
    this.loadOrders()
  },
  
  onPullDownRefresh() {
    this.page = 1
    this.finished = false
    this.loadOrders()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },
  
  methods: {
    getBadgeCount(index) {
      if (index === 0) return this.badgeCount.pending
      return 0
    },
    
    switchTab(index) {
      this.activeTab = index
      this.page = 1
      this.finished = false
      this.orderList = []
      this.loadOrders()
    },
    
    async loadOrders() {
      if (this.loading || this.finished) return
      
      this.loading = true
      
      try {
        const currentTab = this.tabs[this.activeTab]
        const params = {
          current: this.page,
          size: this.pageSize,
          settlementStatus: currentTab.status,  // 结算状态
          role: 'merchant'  // 商家视角
        }
        
        // 待结算订单（申请中）：包含status=5和已退款但有补偿金的订单
        // 已结算订单：不限制status（因为已结算订单status=6已完成）
        // 注意：后端已经在查询条件中处理了status=8且有补偿金的订单，这里不需要额外限制
        
        const pageData = await getPickupOrderPage(params)
        
        //console.log('结算订单分页数据:', pageData)
        
        const records = pageData.records || []
        
        if (this.page === 1) {
          this.orderList = records
        } else {
          this.orderList.push(...records)
        }
        
        this.loading = false
        
        if (records.length < this.pageSize || this.page >= (pageData.pages || 1)) {
          this.finished = true
        }
        
        // 更新角标
        this.updateBadgeCount()
      } catch (error) {
        console.error('加载订单失败:', error)
        this.loading = false
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    
    async updateBadgeCount() {
      // 统计待结算（申请中）数量
      this.badgeCount.pending = this.orderList.filter(o => o.settlementStatus === 1).length
    },
    
    loadMore() {
      if (this.loading || this.finished) return
      this.page++
      this.loadOrders()
    },
    
    goToDetail(order) {
      uni.navigateTo({
        url: `/pages/pickup/detail?orderId=${order.id}`
      })
    },
    
    getCategoryName(order) {
      const types = {
        2: '取快递',
        3: '取外卖',
        4: '代取奶咖'
      }
      return types[order.orderType] || '代取服务'
    },
    
    getSettlementStatusText(status) {
      const texts = {
        0: '待结算',
        1: '申请中',
        2: '已结算'
      }
      return texts[status] || '未知'
    },
    
    getStatusColor(status) {
      const colors = {
        0: '#ff9800',  // 待结算 - 橙色
        1: '#2196f3',  // 申请中 - 蓝色
        2: '#4caf50'   // 已结算 - 绿色
      }
      return colors[status] || '#999'
    },
    
    async handleSettle(order) {
      try {
        uni.showLoading({ title: '加载中...' })
        
        // 获取结算信息（包含收款信息）
        const settlementInfo = await getSettlementInfo(order.id)
        
        uni.hideLoading()
        
        // 设置当前订单并显示弹窗
        this.currentOrder = settlementInfo
        this.showSettlementModal = true
      } catch (error) {
        console.error('获取结算信息失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.msg || '加载失败',
          icon: 'none'
        })
      }
    },
    
    // 关闭结算弹窗
    closeSettlementModal() {
      this.showSettlementModal = false
      this.currentOrder = {}
    },
    
    // 预览收款码
    previewQrCode() {
      if (this.currentOrder.paymentQrCode) {
        uni.previewImage({
          urls: [this.currentOrder.paymentQrCode],
          current: 0
        })
      }
    },
    
    // 确认已转账
    async confirmSettle() {
      uni.showModal({
        title: '确认结算',
        content: `确认已向 ${this.currentOrder.deliveryUserName} 转账 ¥${this.currentOrder.riderEarning} 吗？\n\n此操作不可撤销，请确保已完成转账。`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '结算中...' })
              
              await settleOrder(this.currentOrder.id)
              
              uni.hideLoading()
              this.closeSettlementModal()
              
              uni.showToast({
                title: '结算成功',
                icon: 'success'
              })
              
              // 刷新列表
              setTimeout(() => {
                this.page = 1
                this.finished = false
                this.orderList = []
                this.loadOrders()
              }, 1500)
            } catch (error) {
              console.error('结算失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.msg || '结算失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* Tab栏 */
.tabs {
  background: #fff;
  display: flex;
  padding: 0 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  .tab-text {
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;
  }
  
  .tab-badge {
    position: absolute;
    top: 12rpx;
    right: 20rpx;
    background: #ff4d4f;
    color: #fff;
    font-size: 20rpx;
    padding: 4rpx 8rpx;
    border-radius: 20rpx;
    min-width: 32rpx;
    text-align: center;
  }
  
  &.active {
    .tab-text {
      color: #667eea;
      font-weight: bold;
    }
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 6rpx;
      background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
      border-radius: 3rpx;
    }
  }
}

/* 订单列表 */
.order-list {
  flex: 1;
  height: 0;
  padding: 20rpx;
}

.order-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .order-no-wrapper {
    display: flex;
    align-items: center;
    gap: 12rpx;
  }
  
  .order-no {
    font-size: 24rpx;
    color: #999;
  }
  
  .order-type-tag {
    font-size: 20rpx;
    padding: 4rpx 12rpx;
    border-radius: 8rpx;
    background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
    color: #fff;
    font-weight: bold;
  }
  
  .order-status {
    font-size: 26rpx;
    font-weight: bold;
  }
}

.order-body {
  padding: 24rpx 0;
}

.user-info {
  margin-bottom: 20rpx;
  padding: 16rpx;
  background: #f5f7fa;
  border-radius: 12rpx;
  
  .info-row {
    display: flex;
    align-items: center;
    margin-bottom: 8rpx;
    font-size: 26rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      color: #999;
      min-width: 120rpx;
    }
    
    .value {
      flex: 1;
      color: #333;
    }
  }
}

.settlement-info {
  .amount-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
    font-size: 26rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      color: #999;
    }
    
    .amount {
      color: #333;
      font-weight: 500;
    }
    
    .fee {
      color: #ff6b6b;
      font-weight: 500;
    }
    
    &.refund .fee {
      color: #ff9500;
    }
    
    &.highlight {
      padding-top: 12rpx;
      border-top: 1rpx solid #f0f0f0;
      margin-top: 8rpx;
      
      .label {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
      }
      
      .settlement-amount {
        font-size: 32rpx;
        color: #4caf50;
        font-weight: bold;
      }
    }
  }
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .order-time {
    font-size: 24rpx;
    color: #999;
  }
  
  .order-actions {
    display: flex;
    gap: 16rpx;
  }
}

.btn {
  padding: 12rpx 28rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
  
  &.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
  }
}

/* 空状态 */
.empty {
  padding: 120rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
  
  .empty-icon {
    font-size: 160rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 加载更多 */
.loadmore {
  padding: 40rpx 20rpx;
  text-align: center;
  
  .loadmore-text {
    font-size: 24rpx;
    color: #999;
  }
}

/* 结算详情弹窗 */
.settlement-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 40rpx;
}

.modal-content {
  background: #fff;
  border-radius: 24rpx;
  width: 100%;
  max-width: 640rpx;
  height: 85vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 32rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .modal-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .modal-close {
    font-size: 40rpx;
    color: #999;
    width: 48rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.modal-body {
  flex: 1;
  height: 0;
}

.modal-body-content {
  padding: 32rpx;
  padding-bottom: 60rpx;
}

/* 结算金额区域 */
.settlement-amount-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  padding: 32rpx;
  text-align: center;
  margin-bottom: 32rpx;
  
  .amount-label {
    font-size: 26rpx;
    color: rgba(255, 255, 255, 0.8);
    margin-bottom: 12rpx;
  }
  
  .amount-value {
    font-size: 56rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 8rpx;
  }
  
  .amount-tip {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.7);
  }
}

/* 收款信息区域 */
.payment-info-section,
.order-info-section {
  margin-bottom: 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    padding-bottom: 16rpx;
    border-bottom: 2rpx solid #f0f0f0;
  }
  
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-label {
      font-size: 26rpx;
      color: #999;
      min-width: 140rpx;
      flex-shrink: 0;
    }
    
    .item-value {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
      text-align: right;
      flex: 1;
      word-break: break-all;
      
      &.small {
        font-size: 24rpx;
      }
      
      &.remark {
        text-align: left;
        margin-left: 24rpx;
        color: #666;
        line-height: 1.6;
      }
    }
  }
  
  .info-row-simple {
    padding: 16rpx 0;
    font-size: 24rpx;
    line-height: 1.6;
    
    .row-label {
      color: #999;
    }
    
    .row-value {
      color: #333;
    }
  }
}

/* 收款码区域 */
.qrcode-section {
  margin-top: 32rpx;
  padding: 32rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 16rpx;
  
  .qrcode-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 24rpx;
  }
  
  .qrcode-wrapper {
    background: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    margin: 0 auto;
    width: fit-content;
  }
  
  .qrcode-image {
    width: 450rpx;
    height: 450rpx;
    border-radius: 12rpx;
    display: block;
  }
  
  .qrcode-tip {
    text-align: center;
    font-size: 24rpx;
    color: #666;
    margin-top: 20rpx;
    font-weight: 500;
  }
}

/* 操作按钮 */
.modal-footer {
  display: flex;
  gap: 20rpx;
  padding: 24rpx 32rpx 32rpx;
  border-top: 1rpx solid #f0f0f0;
  
  button {
    flex: 1;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    border: none;
    
    &.btn-cancel {
      background: #f5f5f5;
      color: #666;
    }
    
    &.btn-confirm {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
      font-weight: bold;
    }
  }
}
</style>

